package cn.example.collection;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author July
 * @description 实现两个 Collection 求交集 用Set加速
 * @create 2025-11-19 21:20
 */
public class Intersection {

    public static void main(String[] args) {
        List<Integer> c1 = new ArrayList<>();
        c1.add(1);
        c1.add(2);
        c1.add(3);
        c1.add(4);
        c1.add(5);

        Collection<Integer> c2 = new HashSet<>();
        c2.add(3);
        c2.add(4);
        c2.add(5);
        c2.add(6);
        c2.add(7);

        System.out.println(instersection(c1, c2));
    }

    public static <T> Collection<T> instersection(Collection<T> c1, Collection<T> c2) {
        if (c1 == null || c2 == null || c1.isEmpty() || c2.isEmpty()) {
            return Collections.emptySet();
        }

        // 将其中一个转为 Set 查找更快 O(1)
        Set<T> set2 = new HashSet<>(c2);

        return c1.stream().filter(set2::contains).collect(Collectors.toSet());
    }
}
